#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "Log.hpp"
#include "InetAddr.hpp"

using namespace log_ns;

const static int gsockfd = -1;
const static uint16_t gport = 8888;
const static int gbacklog = 8;

class TcpServer
{
public:
    TcpServer(uint16_t port = gport)
        : _port(port),
          _listensockfd(gsockfd),
          _isrunning(false)
    {
    }
    void InitServer()
    {
        // 1.创建套接字
        _listensockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(FATAL, "socket create error!\n");
            exit(1);
        }
        LOG(INFO, "_listensockfd create success, _sockfd: %d\n", _listensockfd);

        // 2.绑定
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int m = ::bind(_listensockfd, (struct sockaddr *)&local, sizeof(local));
        if (m < 0)
        {
            LOG(FATAL, "bind error!\n");
            exit(2);
        }
        LOG(INFO, "bind success!\n");

        // 3.设为监听状态  因为tcp是面向连接的，所以要不断的获取连接
        if (::listen(_listensockfd, gbacklog) < 0)
        {
            LOG(FATAL, "listen error!\n");
            exit(3);
        }
        LOG(INFO, "listen success!\n");
    }
    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // 4.获取新连接
            int sockfd = ::accept(_listensockfd, (struct sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                // 获取失败了，不会退出，会下一次连接
                LOG(WARNING, "accept error!\n");
                continue;
            }
            InetAddr addr(client);
            LOG(INFO, "get a new link, client info: [%s:%d]\n", addr.Ip().c_str(), addr.Port());

            // 版本0 -- 不靠谱
            Server(sockfd, addr);
        }
        _isrunning = false;
    }
    void Server(int sockfd, InetAddr addr)
    {
        while (1)
        {
            // 5.接收客户端发的信息
            char inbuffer[1024];
            int n = ::read(sockfd, inbuffer, sizeof(inbuffer) - 1);
            if (n > 0)
            {
                // 读取成功
                inbuffer[n] = 0;
                std::string echo_string = "[server echo]# ";
                echo_string += inbuffer;
                // 发回给客户端
                ::write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0)
            {
                // 在IO文件里，读到0，表示读到了结尾
                // 但是网络里， 表示客户端结束
                LOG(INFO, "client [%s:%d] quit!\n", addr.Ip().c_str(), addr.Port());
                break;
            }
            else
            {
                // 读取错误
                LOG(INFO, "read error: [%s:%d]\n", addr.Ip().c_str(), addr.Port());
                break;
            }
        }
        ::close(sockfd);
    }
    ~TcpServer()
    {
    }

private:
    int _listensockfd;
    uint16_t _port;
    bool _isrunning;
};